import { Injectable } from '@nestjs/common';
import * as crypto from 'crypto';
import { readFileSync } from 'fs';
import * as path from 'path';

@Injectable()
export class CryptoService {
    private privateKey: string;

    constructor() {
        // 读取私钥
        const privateKeyPath = path.join(process.cwd(), 'assets/private_key.pem')
        this.privateKey = readFileSync(privateKeyPath, 'utf-8')
    }

    decrypt(encryptedText: string): string {
        const buffer = Buffer.from(encryptedText, 'base64');
        const decrypted = crypto.privateDecrypt(
            {
                key: this.privateKey,
                padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, // 使用 PKCS#1 填充
            },
            buffer,
        );
        return decrypted.toString('utf8');
    }
}